package com.quan.system.web.controller;

import java.util.List;
import java.util.Map.Entry;
import java.util.Set;

import javax.servlet.http.HttpServletRequest;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.MultiValueMap;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import com.quan.base.common.base.web.support.BaseResult;
import com.quan.base.common.base.web.support.controller.BaseController;
import com.quan.oss.common.qiniu.FilePage;
import com.quan.oss.qiniu.client.QiniuOSSClient;

/**
 * 七牛云 OSS
 * @author yhaoquan
 *
 */
@RestController
@RequestMapping(value = "/api/system/oss/qiniu")
public class QiniuOSSController extends BaseController {

	@Autowired
	private QiniuOSSClient ossClient;
	
	/**
	 * 七牛OSS存储，文件统一上传接口
	 * @param request
	 * @param bucket 空间名称
	 * @param dir 目录：weixin/imgage/avatar（目录不存在，自动创建）
	 * @return
	 */
	@PostMapping(value = "/upload")
	public Object upload(HttpServletRequest request, String bucketName, String prefixName) {
		MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request ;
		try {
			//取得MultiValueMap集合
			MultiValueMap<String,MultipartFile> multiFileMap = multipartRequest.getMultiFileMap() ;
			Set<Entry<String, List<MultipartFile>>> entrySet = multiFileMap.entrySet() ;
			for (Entry<String, List<MultipartFile>> entry : entrySet) {
				
				//获取MultipartFile集合
				List<MultipartFile> multipartFiles = entry.getValue() ;
				for (MultipartFile multipartFile : multipartFiles) {
					return this.ossClient.upload(bucketName, multipartFile.getBytes(), multipartFile.getOriginalFilename(), prefixName) ;
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return BaseResult.failure() ;
	}
	
	@GetMapping(value = "/delete")
	public Object delete(String bucketName, String key) {
		this.ossClient.delete(bucketName, key) ;
		return BaseResult.ok() ;
	}
	
	@GetMapping(value = "/deleteBatch")
	public Object deleteBatch(String bucketName, String keys) {
		this.ossClient.deleteBatch(bucketName, keys);
		return BaseResult.ok() ;
	}
	
	@GetMapping(value = "/buckets")
	public Object buckets(FilePage filePage) {
		return this.ossClient.getBuckets() ;
	}
	
	@GetMapping(value = "/list")
	public Object list(FilePage filePage) {
		return this.ossClient.fileList(filePage) ;
	}
	
}
